var config = require("../../config");
var cate = require("../controllers/category");
var nav = require("../controllers/navigator");
var link = require("../controllers/friendlylinks");
var Article = require("../models/article");
var Navigator = require("../models/navigator");
var Setup = require("../models/setup");
var Category = require("../models/category");
var Page = require("../models/page");
var async = require('async');
var laypage=require("laypage")

//新闻列表
exports.list = function (req, res) {
	var pageSize = 20; //每页显示条数
	var page = req.params.num - 1 || 0;
	Article.find().count().exec(function (err, sum) {
		Article.find().limit(pageSize).skip(pageSize*page).sort({_id:-1}).populate("categoryId","CateName").exec(function (err,article) {
			Category.find({}, function (err, category) {
				console.log(article)
				res.render('admin/articleList', {
					title: '新闻列表',
					category: category,
					article: article,
					laypage: laypage({
						curr: req.params.num || 1,
						url: req.url, //必传参数，获取当前页的url
						groups: 5,
						pages: Math.ceil(sum/pageSize), //分页总数你需要通过sql查询得到
						prev: '‹',
						next: '›'
					}),
					pagesize: sum
				})
			})
		});
	});
}

//添加新闻
exports.add = function (req, res) {
	Category.find({original:1}, function (err, category) {
		res.render('admin/articleAdd', {
			title: '添加新闻',
			category: category
		})
	});
}

exports.update = function (req, res) {
	var _article = req.params;
	Category.find({original:1}, function (err, category) {
		Article.findOne({"_id": _article.id}, function (err, article) {
			res.render('admin/articleUpdate', {
				title: '编辑新闻',
				category: category,
				article: article
			})
		});
	});
}

//新闻提交与更新
exports.save = function (req, res) {
	var articleC = req.body;
	var cateArr = articleC.categoryId.split(',')
	var article = {
		title: articleC.title,
		alias: articleC.alias,
		keywords:articleC.keywords,
		remark: articleC.remark,
		categoryId: cateArr[1],
		content: articleC.content,
         typeId:cateArr[0],
		thumbnail:articleC.thumbnail,
		isIndex:!articleC.isIndex?false:true
	}

	if (articleC._id) {
		var id = articleC._id;
		Article.update({
			_id: id
		}, article, function (err, category) {
			res.redirect("/admin/articleList");
		});
	} else {
		delete articleC._id
		Article.create(article, function (err, category) {
			res.redirect("/admin/articleList");
		});
	}

}
//提交与更新
exports.delete = function (req, res) {
	var id = req.params.id;
	Article.remove({
		_id: id
	}, function (err, article) {
		res.redirect("/admin/articleList");
	})
}

//获取浏览次数
var updateclicks= function(id) {
    Article.update({"id":id},{$inc:{clicks:1}},function (err) {
        if (err) {
            console.log(err);
        }
    });
}